package io.gitee.hejiang.action.impl;

import java.sql.Connection;
import java.util.Map;

import com.fasterxml.jackson.databind.JavaType;

import io.gitee.hejiang.action.SwaggerSqlAction;
import io.gitee.hejiang.action.SwaggerSqlActionProvider;
import io.swagger.inflector.models.RequestContext;

public class JavaActionProvider implements SwaggerSqlActionProvider {

	@Override
	public SwaggerSqlAction createAction(Map<String, Object> config) {
		String type = (String) config.get("type");
		if ("java".equalsIgnoreCase(type) || config.containsKey("class")) {
			return new JerseyResourceActionImpl();
		}
		return null;
	}

	static class JerseyResourceActionImpl implements SwaggerSqlAction {
		private SwaggerSqlAction _action;

		@Override
		public void init(Map<String, Object> config, Map<String, JavaType> argumentTypes, SwaggerSqlAction next)
				throws Exception {
			String name = (String) config.get("class");
			Class<?> clazz = Class.forName(name);
			if (SwaggerSqlAction.class.isAssignableFrom(clazz)) {
				_action = (SwaggerSqlAction) clazz.newInstance();
				_action.init(config, argumentTypes, next);
			}
		}

		@Override
		public Object execute(RequestContext request, Connection connection, Map<String, Object> arguments,
				Map<String, Object> context) throws Exception {
			return _action.execute(request, connection, arguments, context);
		}
	}

}